﻿create procedure [dbo].[usp_IIdentityInsert]
	@Name nvarchar(255)
	, @IsAuthenticated bit
	, @AuthenticationType nvarchar(255)
	, @SerializedIIdentityXml xml
as

begin try
	
	set numeric_roundabort off
	
	begin transaction
	
		if not exists(select * from [dbo].[IIdentity] where [Name] = @Name and
		                                                    [IsAuthenticated] = @IsAuthenticated and
		                                                    [AuthenticationType] = @AuthenticationType and
		                                                    [dbo].[CompareXml]([SerializedIIdentityXml], @SerializedIIdentityXml) = 0)
		
			begin
										                              
				insert [dbo].[IIdentity]
				(
					[Name]
					, [IsAuthenticated]
					, [AuthenticationType]
					, [SerializedIIdentityXml]
				)
				values
				(
					@Name
					, @IsAuthenticated
					, @AuthenticationType
					, @SerializedIIdentityXml
				)
				
				select [IIdentityId], [ConcurrencyId], [Created], [Updated] from [dbo].[IIdentity] where @@rowcount > 0 and [IIdentityId] = scope_identity()
			
			end
			
		else
			
			begin
			
				select [IIdentityId], [ConcurrencyId], [Created], [Updated] from [dbo].[IIdentity] where [Name] = @Name and
		                                                                                                 [IsAuthenticated] = @IsAuthenticated and
		                                                                                                 [AuthenticationType] = @AuthenticationType and
				                                                                                         [dbo].[CompareXml]([SerializedIIdentityXml], @SerializedIIdentityXml) = 0
			end
	
	commit transaction

end try
	
begin catch
	if @@trancount > 0
	begin
		rollback transaction;
	end
	execute [dbo].[usp_SqlErrorInsert]
end catch


